/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dataBase;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 * @author ivanpianetti
 */
public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static Session currentSession() {
        HibernateUtil.resetSequenciales();
        return sessionFactory.getCurrentSession();
    }

    public static Integer resetSequenciales() {
        int max = 0;
        try {
            Session s = sessionFactory.getCurrentSession();
            Transaction t = s.beginTransaction();
            Connection conn = s.connection();
            String result = "";
            PreparedStatement stmt = conn.prepareStatement("select restart_sequences()");
            ResultSet resultSet = stmt.executeQuery();
            while (resultSet.next()) {
                result = resultSet.getString(1);
            }
            max = Integer.parseInt(result);
            s.flush();
            t.commit();
        } catch (SQLException ex) {
        } finally {
            return max;
        }
    }

    public static Integer deletAllData() {
        int max = 0;
        try {
            Session s = sessionFactory.getCurrentSession();
            Transaction t = s.beginTransaction();
            Connection conn = s.connection();
            String result = "";
            PreparedStatement stmt = conn.prepareStatement("select deletalldata()");
            ResultSet resultSet = stmt.executeQuery();
            while (resultSet.next()) {
                result = resultSet.getString(1);
            }
            max = Integer.parseInt(result);
            s.flush();
            t.commit();
        } catch (SQLException ex) {
        } finally {
            return max;
        }
    }
}
